/**
 * dao实现类生成器
 * @author dengzongrong
 * @version 1.1
 * @date 2011-10-09
 */
package com.lemon.ai.socket.packets.spiritgame.model.generator;
import static com.lemon.ai.socket.packets.spiritgame.model.generator.utils.StringUtils.*;
import java.util.List;

import com.lemon.ai.socket.packets.spiritgame.model.db.MetaData;
import com.lemon.ai.socket.packets.spiritgame.model.dto.Property;
import com.lemon.ai.socket.packets.spiritgame.model.dto.Table;

public class DtoGenerator extends AbstractGenerator {

	private String PROPERTY_TEMP = 
			"	private TYPE_NAME PROPERTY_NAME;\r";
	private String METHOD_TEMP = 
			"	public void setMETHOD_NAME(TYPE_NAME PROPERTY_NAME) {\r" + 
					"		this.PROPERTY_NAME = PROPERTY_NAME;\r" + 
					"	}\r\r" + 
					"	public TYPE_NAME getMETHOD_NAME() {\r" + 
					"		return this.PROPERTY_NAME;\r" + 
					"	}\r\r";

	public DtoGenerator() {
		super("DtoTemp.txt");
	}

	/**
	 * 根据表名生成Dto代码
	 * 
	 * @param tableName
	 *            表名
	 * @return Dto代码
	 */
	public String generate(Table table) {
		String[] temps = generatePropertiesAndMethods(table);
		return super.temp.
				replace("PACKAGE_NAME", super.prop.getProperty("package")).
				replace("CLASS_NAME", generateClassName(table.getName())).
				replace("IMPORTS", temps[0]).
				replace("PROPERTIES", temps[1]).
				replace("SETS_AND_GETS", temps[2]);
	}

	public String generateFileName(Table table) {
		String className = generateClassName(table.getName());
		return super.prop.getProperty("dir")
				+ super.prop.getProperty("package").replace(".", "\\")
				+ "\\domain\\" + className
				+ ".java";
	}

	/**
	 * 根据表的信息，生成要替换的三个String，分别为imports, properties, methods
	 * @param table
	 * @return new String[]{imports, properties, methods}
	 */
	public String[] generatePropertiesAndMethods(Table table) {
		String imports = "";
		String properties = "";
		String methods = "";
		boolean existDate = false;
		for (int i = 0; i < table.getColumns().size(); i++) {
			Property p = generatePropertyFromColumn(table.getColumns().get(i));
			if ("Date".equals(p.getType()))
				existDate = true;
			properties += PROPERTY_TEMP;
			properties = properties.
					replace("TYPE_NAME", p.getType()).			//成员类型
					replace("PROPERTY_NAME", p.getName());		//成员名字
			methods += METHOD_TEMP;
			methods = methods.
					replace("TYPE_NAME", p.getType()).
					replace("PROPERTY_NAME", p.getName()).
					replace("METHOD_NAME", generateClassName(p.getName()));
		}
		if (existDate)
			imports += "\rimport java.util.Date;\r";
		return new String[]{imports, properties, methods};
	}

	public static void main(String[] args) {
		MetaData meta = MetaData.getInstance();
		List<Table> tables = meta.getTables();
		DtoGenerator g = new DtoGenerator();
		System.out.println(g.generate(tables.get(0)));
	}

}
